package com.haierp.service.logistics.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.Lists;
import com.haierp.util.yitao.YtDimensionCodeUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Sets;
import com.haierp.exception.ErpCommonException;
import com.haierp.mapper.ShippingTrackPxMapper;
import com.haierp.model.ErpOrder;
import com.haierp.model.ShippingOrder;
import com.haierp.model.ShippingTrack;
import com.haierp.model.ShippingTrackPx;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IShippingOrderService;
import com.haierp.service.IShippingTrackPxService;
import com.haierp.service.IShippingTrackService;
import com.haierp.service.logistics.ISiFangService;
import com.haierp.service.xiaohongshu.IXiaohongshuService;
import com.haierp.service.youzan.IYzService;
import com.haierp.util.DimensionCodeUtil;
import com.haierp.util.HttpClientUtil;
import com.haierp.util.MapUtil;
import com.wangzhixuan.commons.utils.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("siFangService")
public class SiFangServiceImpl implements ISiFangService {
    protected Logger logger = LogManager.getLogger(getClass());
    @Autowired
    private IShippingOrderService shippingOrderService;
    @Autowired
    private IShippingTrackService shippingTrackService;
    @Autowired
    private ShippingTrackPxMapper shippingTrackPxMapper;
    @Autowired
    private IShippingTrackPxService shippingTrackPxService;

    @Autowired
    private IYzService yzService;

    @Autowired
    private IXiaohongshuService xiaohongshuService;

    @Autowired
    private IErpOrderService erpOrderService;

    public static final String portlandtoken = "CPRX01A-4528-1106-17PM-1808DEEB48A4";//波特兰token
    public static final String Latoken = "CPRX02A-5646-0202-18AM-F4F5EE3FB5D6";//洛杉矶token
    public static final String NewYorktoken = "CPLC01A-5849-0306-18AM-E53125275854";//纽约token

    @Override
    public String createOrder(Long id, Long companyId) {
        ShippingOrder shippingOrder = shippingOrderService.selectById(id);
        if (shippingOrder == null) {
            throw new ErpCommonException("发货单号异常");
        }
        Map<String, Object> param = new HashMap<String, Object>();
        List<Map<String, Object>> goodsList = new ArrayList<>();
        Map<String, Object> paramData = new HashMap<String, Object>();
        List<ErpOrder> ErpOrderList = shippingOrderService.queryShippingOrderDetail(shippingOrder.getErpOrderId());
        if (companyId.compareTo(ErpOrderList.get(0).getCompanyId()) != 0) {
            throw new ErpCommonException("4px发货-公司ID有误!");
        }
        if (companyId == 1) {
            if (ErpOrderList.get(0).getWarehouseName().equals("波特兰仓")) {
                paramData.put("TerminalCode", "10119");// 波特兰
                param.put("Token", portlandtoken);//正式token
            } else if (ErpOrderList.get(0).getWarehouseName().equals("西雅图仓")) {
                paramData.put("TerminalCode", "10120");// 西雅图
                param.put("Token", portlandtoken);//正式token
            } else if (ErpOrderList.get(0).getWarehouseName().equals("洛杉矶仓")) {
                paramData.put("TerminalCode", "10168");// 洛杉矶
                param.put("Token", Latoken);//洛杉矶token
            } else if (ErpOrderList.get(0).getWarehouseName().equals("纽约仓")) {
                paramData.put("TerminalCode", "2210");// 纽约仓
                param.put("Token", NewYorktoken);//纽约token
            }
            paramData.put("ConsignerName", "miss gu");// 寄件人姓名
            paramData.put("ConsignerMobile", "6513998004");// 寄件人手机号
            if (shippingOrder.getType() == 8) {
                paramData.put("ServiceTypeCode", "SCES");
            } else if (shippingOrder.getType() == 9) {
                paramData.put("ServiceTypeCode", "SSES");
            } else if (shippingOrder.getType() == 21) {
                paramData.put("ServiceTypeCode", "SLES");
            } else if (shippingOrder.getType() == 18) {
                paramData.put("ServiceTypeCode", "RWL");//红酒专线
            } /*else {
				paramData.put("ServiceTypeCode", "SHFS");
			}*/
        } else if (companyId == 2) {
            paramData.put("TerminalCode", "10174");// 艺博站点
            paramData.put("ConsignerName", "Mr wang");// 寄件人姓名
            paramData.put("ConsignerMobile", "5034880078");// 寄件人手机号
            param.put("Token", portlandtoken);//正式token
            if (shippingOrder.getType() == 15) {        //经济A线
                paramData.put("ServiceTypeCode", "SCES");
            } else if (shippingOrder.getType() == 16) {
                paramData.put("ServiceTypeCode", "SSES");
            } else if (shippingOrder.getType() == 22) {
                paramData.put("ServiceTypeCode", "SLES");
            }
        } else {
            throw new ErpCommonException("4px发货-操作有误!");
        }
        ErpOrderList.forEach(erpOrder -> {
            Map<String, Object> goods = new HashMap<String, Object>();
            Map<String, Object> categorymap = MapUtil.getCategoryMap();
            String category = erpOrder.getCategoryName();

            String ItemDeclareTypeCode = "";
            for (Map.Entry<String, Object> entry : categorymap.entrySet()) {
                if (category.equals(entry.getKey())) {
                    ItemDeclareTypeCode = (String) entry.getValue();
                }
            }
            String itemName = erpOrder.getItemName();
            String itemBrand1 = erpOrder.getBrand();
            String itemBrand = erpOrder.getBrand();
            itemBrand = itemBrand.substring(0, itemBrand.indexOf("->"));
            itemBrand1 = itemBrand1.substring(itemBrand1.indexOf("->") + 2, itemBrand1.length());
            itemName = itemName.replace("直邮包税", "");
            itemName = itemName.replace("拼邮包税", "");
            itemName = itemName.replace("男款", "");
            itemName = itemName.replace("女款", "");
            itemName = itemName.replace("成人款", "");
            itemName = itemName.replace("儿童款", "");
            itemName = itemName.replace("大童男款", "");
            itemName = itemName.replace("大童女款", "");
            itemName = itemName.replace("小童女款", "");
            itemName = itemName.replace("小童男款", "");
            itemName = itemName.replace("婴儿款", "");
            itemName = itemName.replace(itemBrand, "");
            itemName = itemName.replace(itemBrand1, "");
            goods.put("ItemSKU", erpOrder.getSkuCode());
            goods.put("ItemDeclareType", ItemDeclareTypeCode);// 商品类目
            goods.put("ItemBrand", erpOrder.getBrand());
            goods.put("ItemName", itemName);
            goods.put("ItemQuantity", erpOrder.getQuantity());
            if (shippingOrder.getType() == 18) {
                goods.put("ItemUnitPrice", erpOrder.getPurchasePrice());
            } else {
                goods.put("ItemUnitPrice", erpOrder.getSalePrice());
            }
            StringBuffer spec = new StringBuffer();
            if (StringUtil.isNotBlank(erpOrder.getColor())) {
                spec.append(",Color:" + erpOrder.getColor());
            }
            if (StringUtil.isNotBlank(erpOrder.getScale())) {
                spec.append(",Size:" + erpOrder.getScale());
            }
            if (ItemDeclareTypeCode.equals("09030400002")) {
                spec.append(",Weight:" + erpOrder.getWeight() + "磅");
            }
            if (!spec.toString().equals("")) {
                goods.put("Specifications", spec.toString().substring(1));
            }
            goodsList.add(goods);
        });
        paramData.put("ShipperOrderNo", shippingOrder.getShippingNo());

        if (shippingOrder.getType() == 18) {
            paramData.put("ItemDeclareCurrency", "USD"); //红酒线路
        } else {
            paramData.put("ItemDeclareCurrency", "CNY");
        }
        paramData.put("ConsigneeName", shippingOrder.getReceiver());
        paramData.put("CountryISO2", "CN");
        paramData.put("ITEMS", goodsList);
        paramData.put("Province", shippingOrder.getReceiverState());
        paramData.put("City", shippingOrder.getReceiverCity());
        paramData.put("District", shippingOrder.getReceiverDistrict());
        paramData.put("ConsigneeStreetDoorNo", shippingOrder.getAddressDetail());
        paramData.put("ConsigneeMobile", shippingOrder.getTelephone());
        paramData.put("ConsigneeIDNumber", shippingOrder.getIdCard());
        paramData.put("OrderWeight", shippingOrder.getSkuWeight());
        param.put("Data", paramData);
        //JSONObject jsonObject = JSONObject.fromObject(param);
        //System.err.println(jsonObject);http://us.transrush.com/agent/createPickupItem(调整)
        JSONObject description = HttpClientUtil.post("http://us.transrush.com/agent/createPickupItem", null, param, "1");
        //System.err.println(description);
        JSONObject shippingNoJson = JSONObject.fromObject(description);
        shippingOrder.setLogisticNo(shippingNoJson.getString("Data"));
        shippingOrderService.updateSelectiveById(shippingOrder);
        if (shippingOrder.getLogisticNo().equals("")) {
            shippingOrder.setMistake(shippingNoJson.getString("Message"));
            shippingOrderService.updateSelectiveById(shippingOrder);
            return shippingNoJson.getString("Message");
        } else {
            if (ErpOrderList.size() == 1 && ErpOrderList.get(0).getSalesName().equals("有赞")) {
                Map<String, String> LogisticsCompanyKey = yzService.youzanGetLogisticsCompany();
                EntityWrapper<ErpOrder> erpList = new EntityWrapper<ErpOrder>();
                erpList.where("target_no={0}", ErpOrderList.get(0).getTargetNo());
                List<ErpOrder> list = erpOrderService.selectList(erpList);
                if (list.size() == 1 && list.get(0).getLogisticType() == 0) {//拼邮的强制不给有赞自动发货
                    yzService.youzanSendLogisticsOnline(ErpOrderList.get(0).getTargetNo(), shippingOrder.getLogisticNo(), LogisticsCompanyKey.get("递四方"));
                }
            } else if (ErpOrderList.get(0).getSalesName().equals("coolforkids")) {
                //Map<String, String> xhsGetLogisticsCompany = xiaohongshuService.xhsGetLogisticsCompany("CFK");
				/*ErpOrder erpOrderTemp = new ErpOrder();
				erpOrderTemp.setTargetNo(ErpOrderList.get(0).getTargetNo());
				ErpOrder erpOrder = erpOrderService.selectOne(erpOrderTemp);*/
                EntityWrapper<ErpOrder> erpList = new EntityWrapper<ErpOrder>();
                erpList.where("target_no={0}", ErpOrderList.get(0).getTargetNo());
                List<ErpOrder> list = erpOrderService.selectList(erpList);
                String path = "/ark/open_api/v0/packages/" + list.get(0).getTargetNo();
                Map<String, String> params = new HashMap<>();
                params.put("status", "shipped");
                params.put("express_company_code", "transrush");
                params.put("express_no", shippingOrder.getLogisticNo());
                try {
                    DimensionCodeUtil.redBookHttpRequest(path, params, "PUT", "CFK");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (ErpOrderList.get(0).getSalesName().equals("一桃平台") || ErpOrderList.get(0).getSalesId().equals(46)) {
                Map<String, Object> params = new HashMap<>();
                String path = "/yitao/api/order/deliver";
                try {
                    EntityWrapper<ErpOrder> erpList = new EntityWrapper<ErpOrder>();
                    erpList.where("target_no={0}", ErpOrderList.get(0).getTargetNo());
                    List<ErpOrder> list = erpOrderService.selectList(erpList);
                    params.put("deliveryCompanyName", "递四方");//快递名称
                    params.put("orderCode", list.get(0).getTargetNo());//一桃订单ID
                    params.put("deliveryNo", shippingOrder.getLogisticNo());//快递编号
                    List<Long> itemIdList = Lists.newArrayList();
                    if (list != null && list.size() != 0) {
                        for (ErpOrder erpOrder : list) {
                            itemIdList.add(erpOrder.getItemId());
                        }
                        if (itemIdList != null && itemIdList.size() != 0) {
                            params.put("itemIdList", itemIdList);
                        }
                    }
                    YtDimensionCodeUtil.yitaoHttpPostRequest(path, params, "post");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }

    @Override
    public void shippingTrack(String shipperOrderNo) throws ParseException {
        if (shipperOrderNo == null) {
            throw new ErpCommonException("物流单号异常");
        }
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> paramData = new HashMap<String, Object>();
        param.put("Token", portlandtoken);
        paramData.put("ShipperOrderNo", shipperOrderNo);
        param.put("Data", paramData);
        JSONObject json = JSONObject.fromObject(param);
        JSONObject jsonObject = HttpClientUtil.post("http://us.transrush.com/Agent/getTrack", null, param, "1");
        String responseNum = (String) jsonObject.get("ResponseCode");
        if (!"10000".equals(responseNum)) {
            throw new ErpCommonException("4PX包裹物流轨迹抓取异常！");
        }
        JSONObject jsonData = jsonObject.getJSONObject("Data");
        String shippingNo = jsonData.getString("ShipperOrderNo");
        String DeliveryNo = jsonData.getString("DeliveryNo");
        ShippingTrack shippingTrack = new ShippingTrack();
        shippingTrack.setShippingNo(shippingNo);
        shippingTrack.setLogisticNo(shippingNo);
        //查询此发货单的物流轨迹
        EntityWrapper<ShippingTrack> selEntityWrapper = new EntityWrapper<ShippingTrack>();
        selEntityWrapper.where("shipping_no={0}", shipperOrderNo);
        List<ShippingTrack> shippingReadyTracks = shippingTrackService.selectList(selEntityWrapper);
        Set<Integer> statusSet = Sets.newHashSet();
        if (shippingReadyTracks.size() > 0) {
            shippingReadyTracks.forEach(item -> {
                statusSet.add(item.getStatus());
            });
        }

        JSONArray jsonArray = jsonData.getJSONArray("TrackingList");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonArrayDetail = jsonArray.getJSONObject(i);
            String trackCode = jsonArrayDetail.getString("TrackStatusCode");
            if (StringUtils.isNotBlank(trackCode)) {
                SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (trackCode.equalsIgnoreCase("PU") && !statusSet.contains(0)) {
                    shippingTrack.setStatus(0);
                    shippingTrack.setInfo("未出库");
                    statusSet.add(0);
                } else if (trackCode.equalsIgnoreCase("LO") && !statusSet.contains(1)) {
                    shippingTrack.setStatus(1);
                    shippingTrack.setOverseaOutTime(date.parse(jsonArrayDetail.getString("TrackTime")));
                    shippingTrack.setInfo("递交航空公司");
                    statusSet.add(1);
                } else if (trackCode.equalsIgnoreCase("FT") && !statusSet.contains(2)) {
                    shippingTrack.setStatus(2);
                    shippingTrack.setOverseaOnTransferTime(date.parse(jsonArrayDetail.getString("TrackTime")));
                    shippingTrack.setInfo("发往国内");
                    statusSet.add(2);
                } else if (trackCode.equalsIgnoreCase("CP") && !statusSet.contains(3)) {
                    shippingTrack.setStatus(3);
                    shippingTrack.setInlandInTime(date.parse(jsonArrayDetail.getString("TrackTime")));
                    shippingTrack.setInfo("抵达国内");
                    statusSet.add(3);
                } else if (trackCode.equalsIgnoreCase("IS") && !statusSet.contains(4)) {
                    shippingTrack.setStatus(4);
                    shippingTrack.setInfo(jsonArrayDetail.getString("TrackContent"));
                    statusSet.add(4);
                } else if (trackCode.equals("OK") && !statusSet.contains(5)) {
                    shippingTrack.setStatus(5);
                    shippingOrderService.updateStatusByShippingNo(shippingNo);
                    shippingTrack.setBuyerSignTime(date.parse(jsonArrayDetail.getString("TrackTime")));
                    shippingTrack.setInfo("用户已签收");
                    statusSet.add(5);
                }
                if (shippingTrack.getStatus() != null) {
                    shippingTrack.setGmtCreate(date.parse(jsonArrayDetail.getString("TrackTime")));
                    shippingTrack.setGmtModify(date.parse(jsonArrayDetail.getString("TrackTime")));
                    shippingTrackService.insertSelective(shippingTrack);
                    shippingTrack.setStatus(null);
                }
            }
        }
        ShippingTrackPx pxon = new ShippingTrackPx();
        pxon.setShipperOrderNo(shipperOrderNo);
        pxon.setDeliveryNo(DeliveryNo);
        pxon.setTrackInfo(jsonArray.toString());
        if (jsonArray.toString().contains("AO")) {
            pxon.setIsGet(1);
        }
        EntityWrapper<ShippingTrackPx> selEntityWrapperPx = new EntityWrapper<ShippingTrackPx>();
        selEntityWrapperPx.where("shipping_no={0}", shipperOrderNo);
        ShippingTrackPx pxMiddle = shippingTrackPxService.selectOne(selEntityWrapperPx);
        if (pxMiddle == null) {
            pxon.setGmtCreate(new Date());
            pxon.setGmtModify(new Date());
            shippingTrackPxMapper.insert(pxon);
        } else {
            pxon.setId(pxMiddle.getId());
            pxon.setGmtModify(new Date());
            shippingTrackPxMapper.updateSelectiveById(pxon);
        }

    }
	
	 /*public static void main(String[] args)  {  
			Map<String, Object> param = new HashMap<String, Object>();
			Map<String, Object> paramData = new HashMap<String, Object>();
			List<String> list = new ArrayList<String>(); 
			list.add("DB493204617US"); 
			String[] toBeStored = list.toArray(new String[list.size()]); 
			String toBeStored[]={"DB493204617US"};
			paramData.put("BillCodes", toBeStored);
			param.put("Data", paramData);
			JSONObject json = JSONObject.fromObject(param);
			JSONObject jsonObject = HttpClientUtil.post("http://us.transrush.com/Agent/getTrack", null, param, "1");
			String responseNum = (String)jsonObject.get("ResponseCode");
			JSONObject jsonData = jsonObject.getJSONObject("Data");
			boolean one =  jsonObject.getJSONObject("Data").isNullObject();
			System.out.println(jsonData);
			String shippingNo = jsonData.getString("ShipperOrderNo");
			String DeliveryNo = jsonData.getString("DeliveryNo");
			ShippingTrack shippingTrack = new ShippingTrack();
			shippingTrack.setShippingNo(shippingNo);
			shippingTrack.setLogisticNo(shippingNo);
			JSONArray jsonArray = jsonData.getJSONArray("TrackingList");
			System.out.println(jsonArray);
	    }*/

}
